<template>
    <div class="table-form-page">
        <div class="form-page-header">
            <div>
                <el-page-header @back="closeWindow" content="立项申请维护" />
            </div>
            <div>
                <el-button v-show="showSaveBtn" type="primary" @click="onSubmit">保存</el-button>
                <el-button v-show="showReviewBtn" type="primary" @click="onReview">审核</el-button>
                <el-button v-show="showSaveBtn" type="warning" @click="onSubcontractAdd">添加分包</el-button>
                <el-button type="default" @click="onPrint">打印</el-button>
            </div>
        </div>
        <div class="form-content">
            <table class="table-class" border="0" cellspacing="0" cellpadding="0">
                <col class="label-col" />
                <col class="content-col" />
                <col class="label-col" />
                <col class="content-col" />
                <tr class="tr-class">
                    <td class="tab-class" colspan="4">项目信息</td>
                </tr>
                <tr class="tr-class">
                    <td class="td-class label-class">项目名称</td>
                    <td class="td-class" colspan="3" style="height: 40px">
                        <el-input
                            v-model="form.projectName"
                            class="form-input-class"
                            placeholder="请选择项目"
                            readonly
                            @click="chooseProject"
                        />
                    </td>
                </tr>
                <tr class="tr-class">
                    <td class="td-class label-class">项目编号</td>
                    <td class="td-class content-class">
                        <el-input v-model="form.projectCode" class="form-input-class" placeholder="请输入项目编号" />
                    </td>
                    <td class="td-class label-class">承担部门</td>
                    <td class="td-class content-class">
                        <el-input
                            v-model="form.departmentName"
                            class="form-input-class"
                            placeholder="请选择"
                            readonly
                            @click="chooseDepartment('1')"
                        />
                    </td>
                </tr>
                <tr class="tr-class">
                    <td class="td-class label-class">业主单位名称</td>
                    <td class="td-class content-class">
                        <el-input
                            v-model="form.clientCompanyName"
                            class="form-input-class"
                            placeholder="请输入业主单位名称"
                        />
                    </td>
                    <td class="td-class label-class">业主单位重要性</td>
                    <td class="td-class content-class">
                        <el-select v-model="form.importanceOfClient" class="form-input-class" placeholder="请选择">
                            <el-option
                                v-for="item in importanceOption"
                                :key="item.value"
                                :label="item.label"
                                :value="item.value"
                            ></el-option>
                        </el-select>
                    </td>
                </tr>
                <tr class="tr-class">
                    <td class="td-class label-class">取得方式</td>
                    <td class="td-class content-class">
                        <el-select v-model="form.wayOfGet" class="form-input-class" placeholder="请选择">
                            <el-option
                                v-for="item in wayOfGetOption"
                                :key="item.value"
                                :label="item.label"
                                :value="item.value"
                            ></el-option>
                        </el-select>
                    </td>
                    <td class="td-class label-class">是否需要签订合同</td>
                    <td class="td-class content-class">
                        <el-select v-model="form.needContract" class="form-input-class" placeholder="请选择">
                            <el-option
                                v-for="item in booleanOption"
                                :key="item.value"
                                :label="item.label"
                                :value="item.value"
                            ></el-option>
                        </el-select>
                    </td>
                </tr>
                <tr class="tr-class">
                    <td class="td-class label-class">项目所在地</td>
                    <td class="td-class content-class">
                        <el-cascader
                            ref="areaRef"
                            v-model="form.projectAddrCode"
                            :options="area"
                            style="width: 100%"
                            placeholder="请选择"
                        />
                    </td>
                    <td class="td-class label-class">详细地址</td>
                    <td class="td-class content-class">
                        <el-input
                            v-model="form.projectAddrSpec"
                            class="form-input-class"
                            placeholder="请输入项目地址"
                        />
                    </td>
                </tr>
                <tr class="tr-class">
                    <td class="td-class label-class">
                        坐标&emsp;(
                        <a href="javascript:void(0)" @click="getAxix">点击获取</a>
                        )
                    </td>
                    <td class="td-class" colspan="3" style="height: 40px">
                        <el-input v-model="form.projectAxis" class="form-input-class" placeholder="请输入坐标" />
                    </td>
                </tr>
                <tr class="tr-class">
                    <td class="td-class label-class">办事处</td>
                    <td class="td-class" colspan="3" style="height: 40px">
                        <el-input
                            v-model="form.branchOffice"
                            class="form-input-class"
                            placeholder="请选择办事处"
                            readonly
                            @click="chooseOffice"
                        />
                    </td>
                </tr>
                <tr class="tr-class">
                    <td class="td-class label-class">项目开始时间</td>
                    <td class="td-class content-class">
                        <el-date-picker
                            v-model="form.projectBeginDate"
                            type="date"
                            value-format="YYYY-MM-DD"
                            class="form-input-class"
                            placeholder="选择日期"
                        />
                    </td>
                    <td class="td-class label-class">项目结束时间</td>
                    <td class="td-class content-class">
                        <el-date-picker
                            v-model="form.projectCompleteDate"
                            type="date"
                            value-format="YYYY-MM-DD"
                            class="form-input-class"
                            placeholder="选择日期"
                        />
                    </td>
                </tr>
                <tr class="tr-class">
                    <td class="td-class label-class">合同额(元)</td>
                    <td class="td-class content-class">
                        <el-input v-model="form.amountOfContract" class="form-input-class" placeholder="请输入合同额" />
                    </td>
                    <td class="td-class label-class">毛利润(元)</td>
                    <td class="td-class content-class">
                        <el-input v-model="form.grossProfit" class="form-input-class" placeholder="请输入毛利润" />
                    </td>
                </tr>
                <tr class="tr-class">
                    <td class="td-class label-class">质量目标</td>
                    <td class="td-class content-class">
                        <el-select v-model="form.goalOfQuality" class="form-input-class" placeholder="请选择">
                            <el-option
                                v-for="item in qualityOption"
                                :key="item.value"
                                :label="item.label"
                                :value="item.value"
                            ></el-option>
                        </el-select>
                    </td>
                    <td class="td-class label-class">项目层级</td>
                    <td class="td-class content-class">
                        <el-select v-model="form.projectLevel" class="form-input-class" placeholder="请选择">
                            <el-option
                                v-for="item in levelOption"
                                :key="item.value"
                                :label="item.label"
                                :value="item.value"
                            ></el-option>
                        </el-select>
                    </td>
                </tr>
                <tr class="tr-class">
                    <td class="td-class label-class">经营计提基数</td>
                    <td class="td-class content-class">
                        <el-input
                            v-model="form.accrualRadix"
                            class="form-input-class"
                            placeholder="请输入经营计提基数"
                        />
                    </td>
                    <td class="td-class label-class">经营计提比例(%)</td>
                    <td class="td-class content-class">
                        <el-input
                            v-model="form.accrualRatio"
                            class="form-input-class"
                            placeholder="请输入经营计提比例"
                        />
                    </td>
                </tr>
                <tr class="tr-class">
                    <td class="td-class label-class">经营费(元)</td>
                    <td class="td-class content-class">
                        <el-input v-model="form.feeOfOperation" class="form-input-class" placeholder="请输入经营费" />
                    </td>
                    <td class="td-class label-class"></td>
                    <td class="td-class content-class"></td>
                </tr>
                <tr class="tr-class">
                    <td class="td-class label-class">项目负责人</td>
                    <td class="td-class content-class">
                        <el-input
                            v-model="form.projectCharge"
                            class="form-input-class"
                            placeholder="请输入项目负责人"
                        />
                    </td>
                    <td class="td-class label-class">项目主管/副总/主任工程师</td>
                    <td class="td-class content-class">
                        <el-input
                            v-model="form.projectSupervisor"
                            class="form-input-class"
                            placeholder="请输入项目主管/副总/主任工程师"
                        />
                    </td>
                </tr>
                <tr class="tr-class">
                    <td class="td-class label-class">主办部门</td>
                    <td class="td-class content-class">
                        <el-input
                            v-model="form.organizeDepartment"
                            class="form-input-class"
                            placeholder="请选择主办部门"
                            @click="chooseDepartment('2')"
                        />
                    </td>
                    <td class="td-class label-class">协办部门</td>
                    <td class="td-class content-class">
                        <el-input
                            v-model="form.assistedDeptartment"
                            class="form-input-class"
                            placeholder="请选择协办部门"
                            @click="chooseDepartment('3')"
                        />
                    </td>
                </tr>
                <tr class="tr-class">
                    <td class="td-class label-class">协办部门负责人</td>
                    <td class="td-class content-class">
                        <el-input
                            v-model="form.assistedCharge"
                            class="form-input-class"
                            placeholder="请输入协办部门负责人"
                        />
                    </td>
                    <td class="td-class label-class">协办部门负责人手机号</td>
                    <td class="td-class content-class">
                        <el-input
                            v-model="form.assistedChargePhone"
                            class="form-input-class"
                            placeholder="请输入协办部门负责人手机号"
                        />
                    </td>
                </tr>
                <tr class="tr-class">
                    <td class="td-class label-class">项目风险说明</td>
                    <td class="td-class" colspan="3" style="height: 40px">
                        <el-input
                            v-model="form.projectRisk"
                            type="textarea"
                            class="form-input-class"
                            :rows="5"
                            placeholder="生产安全风险、经营风险、收款风险"
                        />
                    </td>
                </tr>
                <tr class="tr-class">
                    <td class="td-class label-class">项目工作内容相关技术及人员要求</td>
                    <td class="td-class" colspan="3" style="height: 40px">
                        <el-input
                            v-model="form.projectDemand"
                            type="textarea"
                            class="form-input-class"
                            :rows="5"
                            placeholder="请输入项目工作内容相关技术及人员要求"
                        />
                    </td>
                </tr>
                <tr class="tr-class">
                    <td class="tab-class" colspan="4">项目分包</td>
                </tr>
                <!-- <tr class="tr-class">
                    <td class="td-class label-class">经营性分包</td>
                    <td class="td-class content-class" colspan="3">
                        <el-select v-model="form.isSubContract" class="form-input-class" placeholder="请选择">
                            <el-option v-for="item in subContractOption" :key="item.value" :label="item.label" :value="item.value">
                            </el-option>
                        </el-select>
                    </td>
                </tr> -->
                <tr class="tr-class">
                    <td class="td-class label-class">经营性分包金额(元)</td>
                    <td class="td-class content-class">
                        <el-input
                            v-model="form.subcontractFee"
                            class="form-input-class"
                            placeholder="请输入经营性分包金额"
                        />
                    </td>
                    <td class="td-class label-class">经营性分包占比(%)</td>
                    <td class="td-class content-class">
                        <el-input
                            v-model="form.subcontractRatio"
                            class="form-input-class"
                            placeholder="请输入经营性分包占比"
                        />
                    </td>
                </tr>
                <tr class="tr-class">
                    <td class="td-class label-class">其他分包</td>
                    <td class="td-class" colspan="3">
                        <el-table :data="subcontracts" style="width: 100%; height: 300px">
                            <el-table-column label="拟分包金额">
                                <template #default="scope">
                                    <el-input
                                        v-model="scope.row.count"
                                        class="table-input-class"
                                        placeholder="请输入"
                                    />
                                </template>
                            </el-table-column>
                            <el-table-column label="分包占比(%)">
                                <template #default="scope">
                                    <el-input
                                        v-model="scope.row.ratio"
                                        class="table-input-class"
                                        placeholder="请输入"
                                    />
                                </template>
                            </el-table-column>
                            <el-table-column label="分包情况说明">
                                <template #default="scope">
                                    <el-input
                                        v-model="scope.row.reamrk"
                                        class="table-input-class"
                                        placeholder="请输入"
                                    />
                                </template>
                            </el-table-column>
                        </el-table>
                    </td>
                </tr>
                <tr class="tr-class">
                    <td class="tab-class" colspan="4">附件</td>
                </tr>
                <tr class="tr-class">
                    <td class="td-class" colspan="4">
                        <div v-show="showSaveBtn" style="padding: 10px">
                            <el-upload
                                class="upload-demo"
                                :action="uploadUrl"
                                :headers="uploadHeaders"
                                :on-success="onFileUploadSuccess"
                                :show-file-list="false"
                            >
                                <el-button type="primary">点击上传</el-button>
                            </el-upload>
                        </div>
                        <el-table :data="form.attachments" border>
                            <el-table-column type="index" width="80" label="序号" />
                            <el-table-column prop="fileName" label="文件名" />
                            <el-table-column prop="createTime" label="上传时间" width="200" />
                            <el-table-column fixed="right" label="操作" width="200">
                                <template #default="scope">
                                    <el-button type="primary" @click="handlePreview(scope.row)" size="small">
                                        预览
                                    </el-button>
                                    <el-button
                                        type="danger"
                                        @click.prevent="handleRemove(scope.$index, form.attachments)"
                                        size="small"
                                    >
                                        移除
                                    </el-button>
                                </template>
                            </el-table-column>
                        </el-table>
                    </td>
                </tr>
                <tr class="tr-class">
                    <td class="tab-class" colspan="4">审批流程</td>
                </tr>
                <tr class="tr-class">
                    <td class="td-class" colspan="4">
                        <FlowCpt
                            ref="processRef"
                            :flowType="flowTypeCode"
                            :disabled="!showSaveBtn"
                            :taskId="props.taskId"
                        ></FlowCpt>
                        <FlowOperationCpt
                            v-if="showReviewDialog"
                            :data="form"
                            @close="closeReviewDialog"
                        ></FlowOperationCpt>
                    </td>
                </tr>
                <tr class="tr-class" v-if="showFlowHis">
                    <td class="tab-class" colspan="4">审批记录</td>
                </tr>
                <tr class="tr-class" v-if="showFlowHis">
                    <td class="td-class" colspan="4">
                        <FlowHistoryCpt v-if="showFlowHis" :taskId="props.taskId" />
                    </td>
                </tr>
            </table>
        </div>

        <!-- 项目弹框 -->
        <el-dialog
            title="项目信息"
            v-model="showProjectGridCpt"
            width="80%"
            :lock-scroll="true"
            :close-on-click-modal="false"
            destroy-on-close
        >
            <ProjectGridCpt
                v-if="showProjectGridCpt"
                statuses="'TEMP', 'BID_WIN'"
                @select="projectSelected"
            ></ProjectGridCpt>
        </el-dialog>

        <el-dialog
            width="400px"
            top="20vh"
            title="部门"
            v-model="showDepartment"
            :lock-scroll="true"
            :close-on-click-modal="false"
        >
            <div class="tree-dialog-content">
                <department-tree @select="departmentSelected"></department-tree>
            </div>
        </el-dialog>

        <el-dialog
            width="800px"
            top="10vh"
            title="办事处"
            v-model="showOfficeGridCpt"
            :lock-scroll="true"
            :close-on-click-modal="false"
        >
            <div class="dialog-content">
                <OfficeGridCpt :single="true" @select="officeSelected"></OfficeGridCpt>
            </div>
        </el-dialog>

        <el-dialog
            width="840px"
            top="10vh"
            title="打印预览"
            v-model="showPrint"
            :lock-scroll="true"
            :close-on-click-modal="false"
            :destroy-on-close="true"
        >
            <PrintTemplate :id="props.taskId"></PrintTemplate>
        </el-dialog>
    </div>
</template>
<script setup>
import { ref, toRefs, reactive, onMounted } from 'vue'
import { ElNotification } from 'element-plus'
import http from '@/http.js'
import ProjectGridCpt from '@/components/pub/ProjectGridCpt.vue'
import DepartmentTree from '@/components/bas/DepartmentTree.vue'
import OfficeGridCpt from '@/components/pub/OfficeGridCpt.vue'
import PrintTemplate from '@/print/yunying/ProjectPrint.vue'
import FlowCpt from '@/components/process/FlowCpt.vue'
import FlowOperationCpt from '@/components/process/FlowOperationCpt.vue'
import FlowHistoryCpt from '@/components/process/FlowHistoryCpt.vue'
import area from '@/api/area.json'

const props = defineProps({
    taskId: {
        type: String,
        default: ''
    },
    flowTypeCode: {
        type: String,
        default: 'PROJECT'
    }
})

const emit = defineEmits(['close'])

onMounted(() => {
    if (props.taskId !== '') {
        loadDetail()
    } else {
        showSaveBtn.value = true
    }
})

const showSaveBtn = ref(false)
const showDepartment = ref(false)
const showFlowHis = ref(false)
const showPrint = ref(false)

const areaRef = ref(null)

/**
 * 流程相关
 */
const processRef = ref(null)
const showReviewBtn = ref(false)
const showReviewDialog = ref(false)

const onReview = () => {
    showReviewDialog.value = true
}

const closeReviewDialog = (refresh) => {
    showReviewDialog.value = false
    if (refresh) {
        loadDetail()
    }
}

const importanceOption = ref([
    {
        label: '一般',
        value: 0
    },
    {
        label: '重要',
        value: 1
    }
])

const wayOfGetOption = ref([
    {
        label: '投标',
        value: 0
    },
    {
        label: '委托',
        value: 1
    }
])

const booleanOption = ref([
    {
        label: '否',
        value: 0
    },
    {
        label: '是',
        value: 1
    }
])

const qualityOption = ref([
    {
        label: '精品项目',
        value: 0
    },
    {
        label: '优良项目',
        value: 1
    },
    {
        label: '合格项目',
        value: 2
    }
])

const levelOption = ref([
    {
        label: '所级',
        value: 0
    },
    {
        label: '事业部级',
        value: 1
    }
])

const subContractOption = ref([
    {
        label: '无',
        value: 0
    },
    {
        label: '有',
        value: 1
    }
])

// 表单数据
const form = reactive({
    projectId: '',
    projectCode: '',
    projectName: '',
    departmentId: '',
    departmentCode: '',
    departmentName: '',
    projectAddrCode: '',
    projectAddrName: '',
    projectAddrSpec: '',
    clientCompanyId: '',
    clientCompanyName: '',
    importanceOfClient: '',
    wayOfGet: '',
    branchOffice: '',
    projectBeginDate: '',
    projectCompleteDate: '',
    amountOfContract: '',
    accrualRadix: '',
    accrualRatio: '',
    feeOfOperation: '',
    needContract: '',
    grossProfit: '',
    projectLevel: '',
    goalOfQuality: '',
    projectCharge: '',
    projectSupervisor: '',
    organizeDepartment: '',
    assistedDeptartment: '',
    assistedCharge: '',
    assistedChargePhone: '',
    subcontractDescription: '',
    subcontractType: '',
    projectRisk: '',
    projectDemand: '',
    currentHandler: '',
    flowTypeCode: props.flowTypeCode,
    state: '',
    stateName: '',
    handler: '',
    handlerName: '',
    attachments: [],
    projectAxis: '', //坐标信息
    isSubContract: 0,
    subcontractFee: '',
    subcontractRatio: '',
    subcontractDetail: ''
})

// 分包列表
const subcontracts = ref([])

const closeWindow = () => {
    emit('close')
}

const loadDetail = () => {
    http.fetchForm({
        url: '/yunying/project/findById',
        method: 'get',
        data: {
            id: props.taskId
        }
    }).then((res) => {
        let data = res.data
        if (data.projectAddrCode !== null && data.projectAddrCode !== '') {
            data['projectAddrCode'] = data.projectAddrCode.split(',')
        }
        data['amountOfContract'] = data.amountOfContract == '' ? '' : data.amountOfContract / 100
        data['feeOfOperation'] = data.feeOfOperation == '' ? '' : data.feeOfOperation / 100
        data['grossProfit'] = data.grossProfit == '' ? '' : data.grossProfit / 100
        data['subcontractFee'] = data.subcontractFee == '' ? '' : data.subcontractFee / 100
        Object.assign(form, data)
        subcontracts.value = JSON.parse(data.subcontractDetail)

        // 显示保存按钮条件
        let currentUser = localStorage.getItem('username')
        if (data.state === 0 && data.createBy === currentUser) {
            showSaveBtn.value = true
        } else {
            showSaveBtn.value = false
        }
        // 显示审批按钮条件
        if (data.state !== 0 && data.handler === currentUser) {
            showReviewBtn.value = true
        } else {
            showReviewBtn.value = false
        }
        // 显示流程历史
        showFlowHis.value = true
    })
}

const onSubmit = () => {
    let params = JSON.parse(JSON.stringify(form))
    if (params.projectAddrCode !== null && params.projectAddrCode !== '') {
        params['projectAddrCode'] = params.projectAddrCode.join(',')
        params['projectAddrName'] = areaRef.value.getCheckedNodes()[0].text
    }
    params['amountOfContract'] = params.amountOfContract * 100
    params['feeOfOperation'] = params.feeOfOperation * 100
    params['grossProfit'] = params.grossProfit * 100
    params['subcontractFee'] = params.subcontractFee * 100
    params.subcontractDetail = JSON.stringify(subcontracts.value)
    let processData = processRef.value.processList
    params['flowList'] = processData
    http.fetchJson({
        url: '/yunying/project/save',
        data: params
    }).then((res) => {
        ElNotification({
            title: '提示',
            message: '保存成功',
            type: 'success'
        })
        closeWindow()
    })
}

const onPrint = () => {
    showPrint.value = true
}

const getAxix = () => {
    window.open('https://lbs.amap.com/tools/picker', '_blank')
}

/**
 * 项目选择
 */
const showProjectGridCpt = ref(false)
const chooseProject = () => {
    showProjectGridCpt.value = true
}

const projectSelected = (res) => {
    let project = res[0]
    form.projectId = project.id
    form.projectCode = project.code
    form.projectName = project.name
    form.departmentId = project.departmentId
    form.departmentCode = project.departmentCode
    form.departmentName = project.departmentName
    form.organizeDepartment = project.organizeDepartment
    form.branchOffice = project.branchOffice
    form.wayOfGet = project.wayOfGet
    if (project.addrCode !== null && project.addrCode !== '') {
        form.projectAddrCode = project.addrCode.split(',')
        form.projectAddrName = project.addrName
    }
    form.projectAddrSpec = project.addrSpec
    form.amountOfContract = project.amountOfContract
    form.needContract = 1
    form.accrualRadix = project.accrualRadix
    form.accrualRatio = project.accrualRatio
    form.subcontractFee = project.subcontractFee
    form.subcontractRatio = project.subcontractRatio
    form.assistedDeptartment = project.assistedDeptartment
    showProjectGridCpt.value = false
}

/**
 * 选择部门
 * 1:承担部门、2:主办部门、3:协办部门
 */
const departmentType = ref('')

const chooseDepartment = (type) => {
    departmentType.value = type
    showDepartment.value = true
}

const departmentSelected = (res) => {
    if (departmentType.value === '1') {
        form.departmentId = res.id
        form.departmentCode = res.code
        form.departmentName = res.label
    } else if (departmentType.value === '2') {
        form.organizeDepartment = res.label
    } else if (departmentType.value === '3') {
        form.assistedDeptartment = res.label
    }
    showDepartment.value = false
}

/**
 * 办事处选择
 */
const showOfficeGridCpt = ref(false)

const chooseOffice = () => {
    showOfficeGridCpt.value = true
}

const officeSelected = (res) => {
    form.branchOffice = res.name
    showOfficeGridCpt.value = false
}

const onSubcontractAdd = () => {
    let data = {
        count: '',
        ratio: '',
        remark: ''
    }
    subcontracts.value.push(data)
}

const uploadUrl = ref(import.meta.env.VITE_API_URL + '/sys/file/upload')
const uploadHeaders = reactive({
    Authorization: localStorage.getItem('token')
})

const onFileUploadSuccess = (response) => {
    let json = {
        category: 0,
        fileName: response.data.fileName,
        storageName: response.data.storageName,
        storagePath: response.data.storagePath
    }
    form.attachments.push(json)
}

const handlePreview = (row) => {
    let url = import.meta.env.VITE_API_URL + '/attachment/' + row.storageName
    window.open(url)
}

const handleRemove = (index, rows) => {
    rows.splice(index, 1)
}
</script>
<style scoped>
@import '@/assets/css/table-form.css';
</style>
